﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using VI.Fsc.Common.Util;

namespace VI.Fsc.OperatorGui.Controllers
{
    public class SectionTranslationReader
    {
        private readonly string file;
        private readonly IDirectoryInfoWrapper directoryInfoWrapper;
        private readonly IXDocumentFactory xDocumentFactory;

        public SectionTranslationReader(string file, IDirectoryInfoWrapper directoryInfoWrapper, IXDocumentFactory xDocumentFactory)
        {
            this.directoryInfoWrapper = directoryInfoWrapper;
            this.xDocumentFactory = xDocumentFactory;
            this.file = file;
        }

        public virtual bool GetIsAvailable()
        {
            return directoryInfoWrapper.GetFiles(file).Any();
        }

        public virtual IDictionary<string, string> Read()
        {
            var fileInfo = directoryInfoWrapper.GetFiles(file).Single();

            try
            {
                var xDocument = xDocumentFactory.Create(fileInfo);
                return xDocument
                .Root
                .Elements()
                .ToDictionary(key => key.Elements().First().Value, value => value.Elements().Last().Value);
            }
            catch(XmlException)
            {
                throw new SectionTranslationException();
            }
            catch (NullReferenceException)
            {
                throw new SectionTranslationException();
            }
            catch (InvalidOperationException)
            {
                throw new SectionTranslationException();
            }
            catch(ArgumentException)
            {
                throw new SectionTranslationDoubleKeysException();
            }
        }
    }
}